package com.netsdk.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 文件工具类
 *
 * @author Yan Xu
 * @version 1.0
 * @date 2021/8/7
 * Copyright © goodits
 */
@Slf4j
public class FilePathUtils {

    //路径前加.号代表项目根目录
    private static final String DIR_PATH = "./static/img";

    @SneakyThrows
    public static String getUploadDir()  {
        //如果目录不存在，自动创建文件夹
        File dir = new File(DIR_PATH);
        if (!dir.exists()) {
            //文件
            boolean mkdir = dir.mkdirs();
            if (Boolean.FALSE.equals(mkdir)) {
                log.warn("创建目录{}失败", DIR_PATH);
                return null;
            }
        }
        return dir.getAbsolutePath();
    }

    public static String getUrlPathByFileName(HttpServletRequest request, String fileName) {
        return request.getScheme() + "://" + request.getServerName() + ":" +
                request.getServerPort() + "/img/" + fileName;
    }
}
